import React from 'react';
import { Link } from 'react-router-dom';
import { Card, message } from 'antd';
import PropTypes from 'prop-types';
import { inject, observer } from 'mobx-react';
import NewsList from '../store/new_list'

@inject('newsList') @observer
class PCNewsImgModule extends React.Component {
  constructor() {
    super();
    this.state = {
      news: '',
    }
  }
  componentDidMount() {
    this.getNews()
  }
  // 完成更新
  componentDidUpdate(preProps) {
    // 更新前后的type不一样,重新获取数据
    if (preProps.type !== this.props.type) { this.getNews(); }
  }
  componentWillUnmount() {
    this.props.newsList.deleteImageNews(this.props.type)
  }
  // 获取新闻
  getNews() {
    // 获取新参数，channel和num
    const { type, count } = this.props;
    this.props.newsList.getImageNews(type, count)
      .catch(e => message.error(`出错了，请稍后再试 ${e}`))
  }
  getNewsDataFromBobx() {
    let news = []
    const channel = decodeURIComponent(this.props.type) //eslint-disable-line
    const { newsImageData } = this.props.newsList
    news = !!newsImageData.get(channel) ? newsImageData.get(channel).data : [] // eslint-disable-line
    return news
  }
  asyncBootstrap() {
    return new Promise((resolve) => {
      const { type, count } = this.props;
      this.props.newsList.getImageNews(type, count)
        .then(() => resolve(true))
    })
  }
  render() {
    // 计算每张图片的宽度;
    const news = this.getNewsDataFromBobx()
    const { rowCount } = this.props;
    const width = `${(100 / rowCount) - 3}%`;
    const height = `${70}px`;
    return (
      <div className="news-imgmodule">
        <Card title={this.props.title}>
          <ul className="news-imglist">
            { news.length ?
              news.map(imgItem => (
                <li key={imgItem.id} className="news-imgitem" style={{ width }}>
                  <Link to={`/detail/${imgItem.id}`} style={{ height, display: 'block', overflow: 'hidden' }}>
                    <img src={imgItem.pic} alt={imgItem.title} style={{ minHeight: height }} />
                  </Link>
                  <h3><Link to={`/detail/${imgItem.id}`}>{imgItem.title}</Link></h3>
                  <p>{imgItem.src}</p>
                  <p>{imgItem.time}</p>
                </li>
              )) :
              <div className="loding">
                加载中...
              </div>
            }
          </ul>
        </Card>
      </div>
    )
  }
}
export default PCNewsImgModule;
PCNewsImgModule.propTypes = {
  type: PropTypes.string.isRequired,
  count: PropTypes.string,
  title: PropTypes.string,
  rowCount: PropTypes.string,
  newsList: PropTypes.instanceOf(NewsList),
}
